<?php
/**
 * Created by PhpStorm.
 * User: refar
 * Date: 21-07-21
 * Time: 下午1:17
 */

namespace app\v2\controller;
use ext\MailTemplateV2;
use think\Db;
use think\Exception;
use ext\MailTemplate;
use think\Log;

class Flow extends Common {

    /**
     * showdoc
     * @catalog 接口文档-V2/流程相关/申请
     * @title 样品借出
     * @description 样品借出
     * @method get
     * @param fixed_nos 必选 string fixed_nos=[]
     * @param predictDate 必选 date 预计归还时间
     * @param actualUser 必选 string 实际使用者
     * @param purpose 必选 string 使用目的
     * @return
     * @url http://domain/ems-api/v2/Flow/borrowApply
     * @remark 1.样品申请人->课长; 2.返回状态1代表失败
     */
    public function borrowApply() {

        try {

            // 前端需要把数组变成字符串
            $fixed_nos = json_decode($this->request->param('fixed_nos'));// 转为数组
            $predictDate = $this->request->param('predictDate'); // 预计归还时间
            $actualUser = $this->request->param('actualUser'); // 实际使用者
            $purpose = $this->request->param('purpose'); // 使用目的

            // 需要插入的数据
            $inputData = array();

            for ($i = 0; $i < count($fixed_nos); $i++) {

                $query = Db::table('sms_main_engine')->where('fixed_no', $fixed_nos[$i])
                    ->where('model_status', IN_STORE)->where('user_id', null)->find();
                if (!empty($query)) {
                    // 更新状态
                    $res = Db::table('sms_main_engine')->where('fixed_no', $fixed_nos[$i])
                        ->where('model_status', IN_STORE)->where('user_id', null)
                        ->update([
                            'user_name'    => $this->loginUser['name'],
                            'user_id'      => $this->loginUser['T'],
                            'model_status' => BORROW_REVIEW,
                            'predict_date'  => $predictDate,
                            'actual_user_name'=> $actualUser,
                            'purpose'=>$purpose
                        ]);

                    // 更新成功
                    if (1 == $res) {
                        $tmp['id'] = $query['fixed_no'];
                        $tmp['name'] = $query['MODEL_NAME'];
                        $tmp['predictDate'] = $predictDate;
                        $tmp['desc'] = $query['remark'];

                        $inputData[$query['borrow_classify']][] = $tmp;

                        $this->insertLogRecord([
                            'id'=>null,
                            'fixed_no'=>$query['fixed_no'],
                            'desc'=>LOG_DESC_BORROW,
                            'role'=>$this->loginUser['desc'],
                            'operator'=>$this->loginUser['T'],
                            'type'=>LOG_TYPE_APPLY,
                            'result'=>LOG_RESULT_ADD,
                            'time'=>Db::raw('now()')
                        ]);
                    } else {
                        Log::record('[Flow][borrowApply] update fail ' . $fixed_nos[$i]);
                    }

                }
            }

            // 存入邮件队列表中
            if (!empty($inputData)) {
                foreach ($inputData as $classify => $value) {
                    $to = $this->getAddressByRoleId($this->getManagerRoleIdByClassify($classify, BORROW_REVIEW_CLASSIFY));
                    $depart = $this->loginUser['depart'];
                    $subject = config('mail_header_subject'). MailTemplateV2::$subjectBorrowApply. $depart. ' '
                        .$this->loginUser['name'];
                    $mainBody = MailTemplateV2::getBorrowApply($depart, $this->loginUser['name']);

                    // 插入数据
                    $data = ['id'=>null, 'type'=>getMyType(APPLY), 'main_body'=>$mainBody, 'subject'=>$subject,
                             'from'=>$this->loginUser['email'], 'to'=>json_encode($to), 'table_data' => json_encode($value)];
                    Db::table('ems_mail_queue')->insert($data);
                }
                return apiResponse(SUCCESS, '[Flow][borrowApply] success');
            }

        } catch (Exception $e) {
            Log::record('[Flow][borrowApply] error' . $e->getMessage());
            return apiResponse(ERROR, 'server error');

        }
        return apiResponse(ERROR, 'server error');
    }
    /**
     * showdoc
     * @catalog 接口文档-V2/流程相关/审批
     * @title 样品借出(课长)
     * @description 样品借出(课长)
     * @method get
     * @param fixed_nos 必选 string fixed_nos=[]
     * @param judge 必选 string agree/disagree
     * @param reason 必选 string
     * @return {"status":0,"msg":"[Flow][replyBorrowApplyFromDepart] success","data":[]}
     * @url http://domain/ems-api/v2/Flow/replyBorrowApplyFromDepart
     * @remark 1.课长->同意/拒绝; 2.返回状态1代表失败
     */
    public function replyBorrowApplyFromDepart() {

        try {

            $judge = $this->request->param('judge');
            $fixed_nos = json_decode($this->request->param('fixed_nos'));

            $inputData = array();
            if ('agree' == $judge) {
                // 更新状态到审批通过(待分配)
                for ($i = 0; $i < count($fixed_nos); $i++) {
                    $query = Db::table('sms_main_engine')->where('fixed_no', $fixed_nos[$i])
                        ->where('model_status', BORROW_REVIEW)->whereNotNull('user_id')->find();

                    if (!empty($query)) {
                        $res = Db::table('sms_main_engine')->where('fixed_no', $fixed_nos[$i])
                            ->where('model_status', BORROW_REVIEW)->whereNotNull('user_id')
                            ->update([
                                'approver_id'    => $this->loginUser['T'],
                                'start_date'    => Db::raw('now()'),
                                'approve_date'  => Db::raw('now()'),
                                'approver_name'  => $this->loginUser['name'],
                                'model_status' => ASSIGNING
                            ]);

                        if (1 == $res) {
                            $tmp['id'] = $query['fixed_no'];
                            $tmp['name'] = $query['MODEL_NAME'];
                            $tmp['predictDate'] = empty($query['predict_date']) ? ' - ' :
                                date("Y-m-d", strtotime($query['predict_date']));
                            $tmp['desc'] = $query['remark'];

                            $inputData[] = $tmp;

                            $this->insertLogRecord([
                                'id'=>null,
                                'fixed_no'=>$query['fixed_no'],
                                'desc'=>LOG_DESC_BORROW,
                                'role'=>$this->loginUser['desc'],
                                'operator'=>$this->loginUser['name'],
                                'type'=>LOG_TYPE_CHECK,
                                'result'=>LOG_RESULT_APPROVE,
                                'time'=>Db::raw('now()')
                            ]);
                        } else {
                            Log::record('[Flow][replyBorrowApplyFromDepart] update fail ' . $fixed_nos[$i]);
                        }
                    } else {
                        Log::record('[Flow][replyBorrowApplyFromDepart] no data ' . $fixed_nos[$i]);
                    }
                }
                // 存入邮件队列表中
                if (!empty($inputData)) {
                    $to = $this->getAddressByRoleId(SALE_ADMIN);

                    $subject = config('mail_header_subject'). MailTemplateV2::$subjectBorrowApplyApproveFromSection.
                            $this->loginUser['name'];
                    $mainBody = MailTemplateV2::getReplyApproveBorrowApplyFromDepart();

                    // 插入数据
                    $data = ['id'=>null, 'type'=>getMyType(APPLY), 'main_body'=>$mainBody, 'subject'=>$subject,
                        'from'=>$this->loginUser['email'], 'to'=>json_encode($to), 'table_data' => json_encode($inputData)];

                    $res = Db::table('ems_mail_queue')->insert($data);

                    if (1 == $res) {
                        return apiResponse(SUCCESS, '[Flow][replyBorrowApplyFromDepart] success');
                    }
                    return apiResponse(ERROR, 'server error');
                }

            } else {

                $reason = $this->request->param('reason'); // 拒绝原因
                // 更新状态到在库
                for ($i = 0; $i < count($fixed_nos); $i++) {
                    $query = Db::table('sms_main_engine')->where('fixed_no', $fixed_nos[$i])
                        ->where('model_status', BORROW_REVIEW)->find();

                    if (!empty($query)) {
                        $res = Db::table('sms_main_engine')->where('fixed_no', $fixed_nos[$i])
                            ->where('model_status', BORROW_REVIEW)
                            ->update([
                                'user_name'    => null,
                                'user_id'      => null,
                                'model_status' => IN_STORE,
                                'predict_date'  => null,
                                'actual_user_name'=> null,
                                'purpose'=>null
                            ]);

                        if (1 == $res) {
                            $tmp['id'] = $query['fixed_no'];
                            $tmp['name'] = $query['MODEL_NAME'];
                            $tmp['desc'] = $query['remark'];
                            $tmp['rejectReason'] = $reason;

                            $inputData[$query['user_id']][] = $tmp;

                            $this->insertLogRecord([
                                'id'=>null,
                                'fixed_no'=>$query['fixed_no'],
                                'desc'=>LOG_DESC_BORROW,
                                'role'=>$this->loginUser['desc'],
                                'operator'=>$this->loginUser['name'],
                                'type'=>LOG_TYPE_CHECK,
                                'result'=>LOG_RESULT_REJECT,
                                'reason'=>$reason,
                                'time'=>Db::raw('now()')
                            ]);
                            // 有借出拒绝记录添加
                            $this->updateRejectFlag($query['fixed_no']);
                        } else {
                            Log::record('[Flow][replyBorrowApplyFromDepart] update fail ' . $fixed_nos[$i]);
                        }
                    } else {
                        Log::record('[Flow][replyBorrowApplyFromDepart] no data ' . $fixed_nos[$i]);
                    }
                }

                if (!empty($inputData)) {
                    foreach ($inputData as $key => $value) {
                        $to = $this->getUserInfoById($key);
                        $subject = config('mail_header_subject'). MailTemplate::$subjectBorrowApplyRejectFromSection.
                                $this->loginUser['name'];
                        $mainBody = MailTemplate::getReplyRejectBorrowApplyFromSection($to['login']);

                        // 插入数据
                        $data = ['id'=>null, 'type'=>getMyType(REJECT), 'main_body'=>$mainBody, 'subject'=>$subject,
                                'from'=>$this->loginUser['email'], 'to'=>json_encode(array($to['email'])), // 定时任务判断是数组
                                'table_data' => json_encode($value)];

                        Db::table('ems_mail_queue')->insert($data);
                    }
                    return apiResponse(SUCCESS, '[Flow][replyBorrowApplyFromDepart] success');
                }
            }
        } catch (Exception $e) {
            Log::record('[Flow][replyBorrowApplyFromDepart] error' . $e->getMessage());
            return apiResponse(ERROR, 'server error');
        }
        return apiResponse(ERROR, 'server error');
    }
    /**
     * showdoc
     * @catalog 接口文档-V2/流程相关
     * @title 样品分配
     * @description 样品分配
     * @method get
     * @param fixed_nos 必选 string fixed_nos=[]
     * @param judge 必选 string agree/disagree
     * @param attachment_id 必选 string 上传文件成功返回的id，如果无图片上传则传入null
     * @param reason 必选 string
     * @return {"status":0,"msg":"[Flow][replyBorrowApplyFromSample] success","data":[]}
     * @url http://domain/ems-api/v2/Flow/replyBorrowApplyFromSample
     * @remark 1.样品管理员->同意/拒绝; 2.返回状态1代表失败
     */
    public function replyBorrowApplyFromSample() {
       try {

           $judge = $this->request->param('judge');
           $fixed_nos = json_decode($this->request->param('fixed_nos'));
           $attachment_id = $this->request->param('attachment_id');

           $inputData = array();
           // 分配
           if ('agree' == $judge) {
               for ($i = 0; $i < count($fixed_nos); $i++) {
                   $query = Db::table('sms_main_engine')->where('fixed_no', $fixed_nos[$i])
                       ->where('model_status', ASSIGNING)->find();

                   if (!empty($query)) {
                       $res = Db::table('sms_main_engine')->where('fixed_no', $fixed_nos[$i])
                           ->where('model_status', ASSIGNING)
                           ->update([
                               'model_status' => USING
                           ]);

                       if (1 == $res) {
                           $tmp['id'] = $query['fixed_no'];
                           $tmp['name'] = $query['MODEL_NAME'];
                           $tmp['predictDate'] = empty($query['predict_date']) ? ' - ' :
                               date("Y-m-d", strtotime($query['predict_date']));
                           $tmp['desc'] = $query['remark'];

                           $inputData[$query['user_id']][] = $tmp;

                           // 添加记录到history中
                           $updateQuery = Db::table('sms_main_engine')->where('fixed_no', $fixed_nos[$i])
                                            ->find();
                           $data = ['ID'=>null,
                                    'FIXED_NO'=>$fixed_nos[$i],
                                    'user_id'=>$updateQuery['user_id'],
                                    'user_name'=>$updateQuery['user_name'],
                                    'start_date'=>$updateQuery['start_date'],
                                    'predict_date'=>$updateQuery['predict_date'],
                                    'remark'=>$updateQuery['remark'],
                                    'approver_id'=>$updateQuery['approver_id'],
                                    'approver_name'=>$updateQuery['approver_name'],
                                    'approve_date'=>$updateQuery['approve_date'],
                                    'assign_operator_name'=>$this->loginUser['name'],
                                    'assign_operator_ID'=>$this->loginUser['T'],
                                    'actual_user_name'=>$updateQuery['actual_user_name'],
                                    'instore_proof'=>null,
                                    'assign_proof'=>$attachment_id
                                    ];

                           $r = Db::table('sms_borrow_history')->insert($data);
                           if (1 != $r) {
                               Log::record('[Flow][replyBorrowApplyFromSample] add history fail ' . $fixed_nos[$i]);
                           }

                           $this->insertLogRecord([
                               'id'=>null,
                               'fixed_no'=>$query['fixed_no'],
                               'desc'=>LOG_DESC_ASSIGN,
                               'role'=>$this->loginUser['desc'],
                               'operator'=>$this->loginUser['name'],
                               'type'=>LOG_TYPE_CHECK,
                               'result'=>LOG_RESULT_APPROVE,
                               'time'=>Db::raw('now()')
                           ]);
                       } else {
                           Log::record('[Flow][replyBorrowApplyFromSample] update fail ' . $fixed_nos[$i]);
                       }
                   } else {
                       Log::record('[Flow][replyBorrowApplyFromSample] no data ' . $fixed_nos[$i]);
                   }
               }

               if (!empty($inputData)) {
                   foreach ($inputData as $key => $value) {
                       $to = $this->getUserInfoById($key);
                       $subject = config('mail_header_subject'). MailTemplateV2::$subjectBorrowApplyApproveFromSample.
                            $this->loginUser['name'];
                       $mainBody = MailTemplateV2::getReplyApproveBorrowApplyFromSample($to['login']);

                       // 插入数据
                       $data = ['id'=>null, 'type'=>getMyType(APPLY), 'main_body'=>$mainBody, 'subject'=>$subject,
                           'from'=>$this->loginUser['email'], 'to'=>json_encode(array($to['email'])),
                           'table_data' => json_encode($value)];

                       Db::table('ems_mail_queue')->insert($data);
                   }
                   return apiResponse(SUCCESS, '[Flow][replyBorrowApplyFromSample] success');
               }
           } else {

               $reason = $this->request->param('reason'); // 拒绝原因
               for ($i = 0; $i < count($fixed_nos); $i++) {
                   $query = Db::table('sms_main_engine')->where('fixed_no', $fixed_nos[$i])
                       ->where('model_status', ASSIGNING)->find();

                   if (!empty($query)) {
                       $res = Db::table('sms_main_engine')->where('fixed_no', $fixed_nos[$i])
                           ->where('model_status', ASSIGNING)
                           ->update([
                               'user_name'    => null,
                               'user_id'      => null,
                               'approver_id'    => null,
                               'start_date'    => null,
                               'approve_date'  => null,
                               'approver_name'  => null,
                               'model_status' => IN_STORE,
                               'predict_date'  => null,
                               'actual_user_name'=> null,
                               'purpose'=>null
                           ]);

                       if (1 == $res) {
                           $tmp['id'] = $query['fixed_no'];
                           $tmp['name'] = $query['MODEL_NAME'];
                           $tmp['rejectReason'] = $reason;
                           $tmp['desc'] = $query['remark'];

                           $inputData[$query['user_id']][] = $tmp;

                           $this->insertLogRecord([
                               'id'=>null,
                               'fixed_no'=>$query['fixed_no'],
                               'desc'=>LOG_DESC_ASSIGN,
                               'role'=>$this->loginUser['desc'],
                               'operator'=>$this->loginUser['name'],
                               'type'=>LOG_TYPE_CHECK,
                               'result'=>LOG_RESULT_REJECT,
                               'reason'=>$reason,
                               'time'=>Db::raw('now()')
                           ]);
                           $this->updateRejectFlag($query['fixed_no']);
                       } else {
                           Log::record('[Flow][replyBorrowApplyFromSample] update fail ' . $fixed_nos[$i]);
                       }
                   } else {
                       Log::record('[Flow][replyBorrowApplyFromSample] no data ' . $fixed_nos[$i]);
                   }
               }
               if (!empty($inputData)) {
                   foreach ($inputData as $key => $value) {
                       $to = $this->getUserInfoById($key);
                       $subject = config('mail_header_subject'). MailTemplateV2::$subjectBorrowApplyRejectFromSample.
                           $this->loginUser['name'];
                       $mainBody = MailTemplateV2::getReplyRejectBorrowApplyFromSample($to['login']);

                       // 插入数据
                       $data = ['id'=>null, 'type'=>getMyType(REJECT), 'main_body'=>$mainBody, 'subject'=>$subject,
                           'from'=>$this->loginUser['email'], 'to'=>json_encode(array($to['email'])), // 定时任务判断是数组
                           'table_data' => json_encode($value)];

                       Db::table('ems_mail_queue')->insert($data);
                   }
                   return apiResponse(SUCCESS, '[Flow][replyBorrowApplyFromSection] success');
               }
           }

       } catch (Exception $e) {
           Log::record('[Flow][replyBorrowApplyFromSample] error' . $e->getMessage());
           return apiResponse(ERROR, 'server error');
       }
        return apiResponse(ERROR, 'server error');
    }

    /**
     * showdoc
     * @catalog 接口文档-V2/流程相关/取消
     * @title 样品借出
     * @description 样品借出
     * @method get
     * @param fixed_nos 必选 string fixed_nos=""
     * @return {"status":0,"msg":"[Flow][cancelBorrow] success","data":[]}
     * @url http://domain/ems-api/v2/Flow/cancelBorrow
     * @remark fixed_nos 为单项
     */
    public function cancelBorrow() {
        try {
            $fixed_nos = $this->request->param('fixed_nos');

            $query = Db::table('sms_main_engine')->where('fixed_no', $fixed_nos)
                ->where('model_status', BORROW_REVIEW)->find();
            if (!empty($query)) {

                $this->insertLogRecord([
                    'id'=>null,
                    'fixed_no'=>$query['fixed_no'],
                    'desc'=>LOG_DESC_BORROW,
                    'role'=>$this->loginUser['desc'],
                    'operator'=>$query['user_name'],
                    'type'=>LOG_TYPE_APPLY,
                    'result'=>LOG_RESULT_CANCEL,
                    'time'=>Db::raw('now()')
                ]);

                // 更新状态
                $res = Db::table('sms_main_engine')->where('fixed_no', $fixed_nos)
                    ->where('model_status', BORROW_REVIEW)
                    ->update([
                        'user_name'    => null,
                        'user_id'      => null,
                        'approver_id'    => null,
                        'start_date'    => null,
                        'approve_date'  => null,
                        'approver_name'  => null,
                        'model_status' => IN_STORE,
                        'predict_date'  => null,
                        'actual_user_name'=> null,
                        'purpose'=>null
                    ]);

                // 更新不成功
                if (1 != $res) {
                    Log::record('[Flow][cancelBorrow] update fail ' . $fixed_nos);
                    return apiResponse(ERROR, 'server error');
                }
            }
            return apiResponse(SUCCESS, '[Flow][cancelBorrow] success');

        } catch (Exception $e) {
            Log::record('[Flow][cancelBorrow] error' . $e->getMessage());
            return apiResponse(ERROR, 'server error');

        }
    }

    /**
     * showdoc
     * @catalog 接口文档-V2/流程相关
     * @title 样品归还
     * @description 样品归还
     * @method get
     * @param fixed_nos 必选 string fixed_nos=[]
     * @param attachment_id 必选 string 上传文件成功返回的id，如果没有图片则传入null
     * @return {"status":0,"msg":"[Flow][returnSample] success","data":[]}
     * @url http://domain/ems-api/v2/Flow/returnSample
     * @remark 1.样品管理员->归还; 2.返回状态1代表失败
     */
    public function returnSample() {
        try {

            $fixed_nos = json_decode($this->request->param('fixed_nos'));
            $attachment_id = $this->request->param('attachment_id');

            $inputData = array();

            for ($i = 0; $i < count($fixed_nos); $i++) {
                $query = Db::table('sms_main_engine')->where('fixed_no', $fixed_nos[$i])
                    ->where('model_status', USING)->find();

                if (!empty($query)) {
                    $res = Db::table('sms_main_engine')->where('fixed_no', $fixed_nos[$i])
                        ->where('model_status', USING)
                        ->update([
                            'user_name'    => null,
                            'user_id'      => null,
                            'approver_id'    => null,
                            'start_date'    => null,
                            'approve_date'  => null,
                            'approver_name'  => null,
                            'predict_date'  => null,
                            'model_status' => IN_STORE,
                            'actual_user_name'=> null,
                            'purpose'=>null
                        ]);

                    if (1 == $res) {
                        $tmp['id'] = $query['fixed_no'];
                        $tmp['name'] = $query['MODEL_NAME'];
                        $tmp['desc'] = $query['remark'];

                        $inputData[$query['user_id']][] = $tmp;

                        // 更新记录到history中
                        $data = [
                            'end_date' => Db::raw('now()'), // 使用结束时间
                            'confirm_operator_id'=>$this->loginUser['T'],
                            'confirm_operator_name'=>$this->loginUser['name'],
                            'instore_proof'=>$attachment_id
                        ];

                        $r = Db::table('sms_borrow_history')->where('fixed_no', $fixed_nos[$i])
                                        ->whereNull('end_date')->whereNull('confirm_operator_id')
                                        ->whereNull('confirm_operator_name')->update($data);
                        if (1 != $r) {
                            Log::record('[Flow][returnSample] update history fail ' . $fixed_nos[$i]);
                        }

                        $this->insertLogRecord([
                            'id'=>null,
                            'fixed_no'=>$query['fixed_no'],
                            'desc'=>LOG_DESC_RETURN,
                            'role'=>$this->loginUser['desc'],
                            'operator'=>$this->loginUser['name'],
                            'type'=>'-',
                            'result'=>'-',
                            'time'=>Db::raw('now()')
                        ]);
                    } else {
                        Log::record('[Flow][returnSample] update fail ' . $fixed_nos[$i]);
                    }
                } else {
                    Log::record('[Flow][returnSample] no data ' . $fixed_nos[$i]);
                }
            }

            if (!empty($inputData)) {
                foreach ($inputData as $key => $value) {
                    $to = $this->getUserInfoById($key);
                    $subject = config('mail_header_subject'). MailTemplate::$subjectReturnSample.
                        $this->loginUser['name'];
                    $mainBody = MailTemplate::getReturnSample($to['login']);

                    // 插入数据
                    $data = ['id'=>null, 'type'=>getMyType(FLOW), 'main_body'=>$mainBody, 'subject'=>$subject,
                        'from'=>$this->loginUser['email'], 'to'=>json_encode(array($to['email'])), // 定时任务判断是数组
                        'table_data' => json_encode($value)];

                    Db::table('ems_mail_queue')->insert($data);
                }
                return apiResponse(SUCCESS, '[Flow][returnSample] success');
            }

        } catch (Exception $e) {
            Log::record('[Flow][returnSample] error' . $e->getMessage());
            return apiResponse(ERROR, 'server error');
        }
        return apiResponse(ERROR, 'server error');
    }

    /**
     * showdoc
     * @catalog 接口文档-V2/流程相关/申请
     * @title 样品删除
     * @description 样品删除
     * @method get
     * @param fixed_nos 必选 string fixed_nos=[]
     * @return {"status":0,"msg":"[Flow][deleteApply] success","data":[]}
     * @url http://domain/ems-api/v2/Flow/deleteApply
     * @remark 1.样品管理员(删除申请)->课长; 2.返回状态1代表失败
     */
    public function deleteApply() {
        try {

            // 前端需要把数组变成字符串
            $fixed_nos = json_decode($this->request->param('fixed_nos'));// 转为数组

            // 需要插入的数据
            $inputData = array();

            for ($i = 0; $i < count($fixed_nos); $i++) {

                $query = Db::table('sms_main_engine')->where('fixed_no', $fixed_nos[$i])
                    ->where('model_status', IN_STORE)->where('user_id', null)->find();
                if (!empty($query)) {
                    // 更新状态
                    $res = Db::table('sms_main_engine')->where('fixed_no', $fixed_nos[$i])
                        ->where('model_status', IN_STORE)->where('user_id', null)
                        ->update([
                            'model_status'    => DELETE_REVIEW_V2,
                            'scrap_operator'      => $this->loginUser['name'], // 老系统存入的就为用户名
                            'scrap_date' => Db::raw('now()'),
                        ]);

                    // 更新成功
                    if (1 == $res) {
                        $tmp['id'] = $query['fixed_no'];
                        $tmp['name'] = $query['MODEL_NAME'];
                        $tmp['desc'] = $query['remark'];

                        $inputData[$query['borrow_classify']][] = $tmp;

                        $this->insertLogRecord([
                            'id'=>null,
                            'fixed_no'=>$query['fixed_no'],
                            'desc'=>LOG_DESC_DELETE,
                            'role'=>$this->loginUser['desc'],
                            'operator'=>$this->loginUser['name'],
                            'type'=>LOG_TYPE_APPLY,
                            'result'=>LOG_RESULT_ADD,
                            'time'=>Db::raw('now()')
                        ]);
                    } else {
                        Log::record('[Flow][deleteApply] update fail ' . $fixed_nos[$i]);
                    }

                }
            }

            // 存入邮件队列表中
            if (!empty($inputData)) {
                foreach ($inputData as $classify => $value) {
                    $to = $this->getAddressByRoleId($this->getManagerRoleIdByClassify($classify, DELETE_REVIEW_CLASSIFY));
                    $subject = config('mail_header_subject'). MailTemplateV2::$subjectDeleteApply.
                        $this->loginUser['depart']. ' '.$this->loginUser['name'];
                    $mainBody = MailTemplateV2::getDeleteApply($this->loginUser['depart'], $this->loginUser['name']);

                    // 插入数据
                    $data = ['id'=>null, 'type'=>getMyType(FLOW), 'main_body'=>$mainBody, 'subject'=>$subject,
                        'from'=>$this->loginUser['email'], 'to'=>json_encode($to), 'table_data' => json_encode($value)];
                    Db::table('ems_mail_queue')->insert($data);
                }
                return apiResponse(SUCCESS, '[Flow][deleteApply] success');
            }

        } catch (Exception $e) {
            Log::record('[Flow][deleteApply] error' . $e->getMessage());
            return apiResponse(ERROR, 'server error');

        }
        return apiResponse(ERROR, 'server error');

    }
    /**
     * showdoc
     * @catalog 接口文档-V2/流程相关/审批
     * @title 样品删除(课长)
     * @description 样品删除(课长)
     * @method get
     * @param fixed_nos 必选 string fixed_nos=[]
     * @param judge 必选 string agree/disagree
     * @return {"status":0,"msg":"[Flow][replyDeleteApplyFromSection] success","data":[]}
     * @url http://domain/ems-api/v2/Flow/replyDeleteApplyFromDepart
     * @remark 1.课长->同意/拒绝; 2.返回状态1代表失败
     */
    // 老系统删除审批 【同意】 【不同意】 都不发送邮件
    public function replyDeleteApplyFromDepart() {
        try {
            $judge = $this->request->param('judge');
            $fixed_nos = json_decode($this->request->param('fixed_nos'));

            $inputData = array();
            if ('agree' == $judge) {
                // 课长同意， 则删除机器
                for ($i = 0; $i < count($fixed_nos); $i++) {
                    $query = Db::table('sms_main_engine')->where('fixed_no', $fixed_nos[$i])
                        ->where('model_status', DELETE_REVIEW_V2)->find();

                    if (!empty($query)) {
                        $res = Db::table('sms_main_engine')->where('fixed_no', $fixed_nos[$i])
                            ->where('model_status', DELETE_REVIEW_V2)
                            ->delete();
                        if (1 == $res) {
                            $tmp['id'] = $query['fixed_no'];
                            $tmp['name'] = $query['MODEL_NAME'];
                            $tmp['desc'] = $query['remark'];

                            $inputData[] = $tmp;

                            $this->insertLogRecord([
                                'id'=>null,
                                'fixed_no'=>$query['fixed_no'],
                                'desc'=>LOG_DESC_DELETE,
                                'role'=>$this->loginUser['desc'],
                                'operator'=>$this->loginUser['name'],
                                'type'=>LOG_TYPE_CHECK,
                                'result'=>LOG_RESULT_APPROVE,
                                'time'=>Db::raw('now()')
                            ]);
                        } else {
                            Log::record('[Flow][replyDeleteApplyFromDepart] delete fail ' . $fixed_nos[$i]);
                        }
                    } else {
                        Log::record('[Flow][replyDeleteApplyFromDepart] no data ' . $fixed_nos[$i]);
                    }
                }
                // 存入邮件队列表中
                if (!empty($inputData)) {
                    $to = $this->getAddressByRoleId(SALE_ADMIN);

                    $subject = config('mail_header_subject'). MailTemplateV2::$subjectDeleteApplyApproveFromDepart.
                             $this->loginUser['name'];
                    $mainBody = MailTemplateV2::getDeleteApproveFromDepart();

                    // 插入数据
                    $data = ['id'=>null, 'type'=>getMyType(FLOW), 'main_body'=>$mainBody, 'subject'=>$subject,
                        'from'=>$this->loginUser['email'], 'to'=>json_encode($to), 'table_data' => json_encode($inputData)];

                    $res = Db::table('ems_mail_queue')->insert($data);

                    if (1 == $res) {
                        return apiResponse(SUCCESS, '[Flow][replyDeleteApplyFromDepart] success');
                    }
                    return apiResponse(ERROR, 'server error');
                }

            } else {
                // 更新状态到在库
                for ($i = 0; $i < count($fixed_nos); $i++) {
                    $query = Db::table('sms_main_engine')->where('fixed_no', $fixed_nos[$i])
                        ->where('model_status', DELETE_REVIEW_V2)->find();

                    if (!empty($query)) {
                        $res = Db::table('sms_main_engine')->where('fixed_no', $fixed_nos[$i])
                            ->where('model_status', DELETE_REVIEW_V2)
                            ->update([
                                'scrap_operator'      => null, // 老系统还会更新approve_id等根本没啥卵用
                                'scrap_date' => null,
                                'model_status'    => IN_STORE,
                            ]);

                        if (1 == $res) {
                            $tmp['id'] = $query['fixed_no'];
                            $tmp['name'] = $query['MODEL_NAME'];
                            $tmp['desc'] = $query['remark'];

                            $inputData[] = $tmp;

                            $this->insertLogRecord([
                                'id'=>null,
                                'fixed_no'=>$query['fixed_no'],
                                'desc'=>LOG_DESC_DELETE,
                                'role'=>$this->loginUser['desc'],
                                'operator'=>$this->loginUser['name'],
                                'type'=>LOG_TYPE_CHECK,
                                'result'=>LOG_RESULT_REJECT,
                                'time'=>Db::raw('now()')
                            ]);
                        } else {
                            Log::record('[Flow][replyDeleteApplyFromDepart] update fail ' . $fixed_nos[$i]);
                        }
                    } else {
                        Log::record('[Flow][replyDeleteApplyFromDepart] no data ' . $fixed_nos[$i]);
                    }
                }

                if (!empty($inputData)) {
                    $to = $this->getAddressByRoleId(SALE_ADMIN);

                    $subject = config('mail_header_subject'). MailTemplateV2::$subjectDeleteApplyRejectFromDepart.
                                    $this->loginUser['name'];
                    $mainBody = MailTemplateV2::getDeleteRejectFromDepart();

                    // 插入数据
                    $data = ['id'=>null, 'type'=>getMyType(FLOW), 'main_body'=>$mainBody, 'subject'=>$subject,
                        'from'=>$this->loginUser['email'], 'to'=>json_encode($to), 'table_data' => json_encode($inputData)];

                    $res = Db::table('ems_mail_queue')->insert($data);

                    if (1 == $res) {
                        return apiResponse(SUCCESS, '[Flow][replyDeleteApplyFromDepart] success');
                    }
                    return apiResponse(ERROR, 'server error');
                }
            }
        } catch (Exception $e) {
            Log::record('[Flow][replyDeleteApplyFromDepart] error' . $e->getMessage());
            return apiResponse(ERROR, 'server error');
        }
        return apiResponse(ERROR, 'server error');
    }

    private function getManagerRoleIdByClassify($classify, $type) {
        $c = json_decode($type);

        $r = array();
        foreach ($c as $key => $value) {
            if (in_array($classify, $value)) {
               $r[] = $key;
            }

        }
        return $r;
    }

    private function getAddressByRoleId($roleId) {
        $address = array();
        try {
            $res = Db::table('users')->whereIn('role_id', $roleId)
                ->whereIn('department', $this->getDepartV2())->field('email')->select();

            foreach ($res as $k => $v) {
                $address[] = $v['email'];
            }
            return $address;
        } catch (Exception $e) {
            Log::record('[Flow][getDepartAddress] error' . $e->getMessage());
            return apiResponse(ERROR, 'server error');
        }
    }

    private function insertLogRecord($data) {
        try {
            Db::table('sms_log_record')->insert($data);

        } catch (Exception $e) {
            Log::record('[Flow][insertLogRecord] error' . $e->getMessage());
            return apiResponse(ERROR, 'server error');
        }

    }

    private function updateRejectFlag($fixed_no) {
        try {
            Db::table('sms_main_engine')->where('fixed_no', $fixed_no)->update(['reject_flag' => '1']);

        } catch (Exception $e) {
            Log::record('[Flow][updateRejectFlag] error' . $e->getMessage());
            return apiResponse(ERROR, 'server error');
        }

    }

}